package com.aaa.producter;

import com.aaa.entity.Info;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/5/20 9:49
 * @description：消息的生产者，
 * 接收agent发送过来的服务器性能数据，并且将数据保存到kafka消息队列中
 * @modified By：
 * @version: 1.0
 */
@Controller
@RequestMapping("info")
@Slf4j
public class MyProducter {
    @Autowired
    private KafkaTemplate kafkaTemplate;
    /**
     * 接收agent发送过来的服务器性能数据，
     * 并且将数据保存到kafka消息队列中
     * @param info
     * @return
     */
    @RequestMapping("addInfo")
    @ResponseBody
    public Object addInfo(@RequestBody Info info, HttpServletRequest request){
        //jackson的工具类，springboot自带
        ObjectMapper objectMapper = new ObjectMapper();
    //    System.out.println("producter_info信息："+info.toString());
        //request中包含有远程客户端的ip地址
        String remoteAddr = request.getRemoteAddr();
        /* log.info("远程客户端的ip地址："+remoteAddr);*/
         //将ip地址绑定到info实体类中
        info.setIpAddress(remoteAddr);
        //并且将数据保存到kafka消息队列中
        try {
            //objectMapper.writeValueAsString(info) ，将info实体类转换成字符串
            kafkaTemplate.send("mytopic",objectMapper.writeValueAsString(info));
            log.info("生产者打印的消息："+info);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return info;
    }
}
